package com.jingan.nursinghome.regulatory.separate

import android.app.Activity
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.Rect
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.RecyclerView.Adapter
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import cn.android.support.v7.lib.sin.crown.base.BaseActivity
import cn.android.support.v7.lib.sin.crown.base.BaseListenner
import cn.android.support.v7.lib.sin.crown.kotlin.anko.Titlebar
import cn.android.support.v7.lib.sin.crown.kotlin.base.BaseDialog
import cn.android.support.v7.lib.sin.crown.kotlin.common.Toast
import cn.android.support.v7.lib.sin.crown.kotlin.common.px
import cn.android.support.v7.lib.sin.crown.kotlin.dialog.AlertDialog
import cn.android.support.v7.lib.sin.crown.kotlin.utils.JSonUtils
import cn.android.support.v7.lib.sin.crown.kotlin.utils.SelectorUtils
import cn.android.support.v7.lib.sin.crown.kotlin.widget.RoundTextView
import cn.android.support.v7.lib.sin.crown.utils.AssetsUtils
import cn.android.support.v7.lib.sin.crown.utils.ProportionUtils
import cn.android.support.v7.lib.sin.crown.view.AutoLinefeedLayout
import com.jingan.nursinghome.regulatory.R
import com.jingan.nursinghome.regulatory.data.MicrometerTable
import com.jingan.nursinghome.regulatory.dialog.micrometertable.LoginDialog
import com.jingan.nursinghome.regulatory.separate.bean.SelectXj
import com.jingan.nursinghome.regulatory.separate.bean.tmfl
import org.jetbrains.anko.*
import org.jetbrains.anko.recyclerview.v7.recyclerView
import org.jetbrains.anko.sdk25.coroutines.onCheckedChange
import org.jetbrains.anko.sdk25.coroutines.onClick
import java.util.ArrayList

/**
 * 分开巡检
 * Created by 彭治铭 on 2018/6/25.
 */
class SeparateDialog(var activity: BaseActivity) : BaseDialog(activity) {

    private var exitTime: Long = 0
    open var exitInfo = "再点一次退出"

    init {
        isDarkmode(true).isDismiss(false).isLocked(true) {
            if (System.currentTimeMillis() - exitTime > 2000) {
                Toast.show(exitInfo)
                exitTime = System.currentTimeMillis()
            } else {
                android.os.Process.killProcess(android.os.Process.myPid())//退出应用（杀进程）
            }
        }
    }


    var recyclerView: RecyclerView? = null
    var adapter: Adapter<MyViewHolder>? = null
    override fun listener() {
        update()
        if (adapter == null) {
            adapter = MyAdapter(activity, this, list)
            recyclerView?.adapter = adapter
        }
        adapter?.notifyDataSetChanged()
        recyclerView?.addItemDecoration(object : RecyclerView.ItemDecoration() {
            override fun getItemOffsets(outRect: Rect?, itemPosition: Int, parent: RecyclerView?) {
                super.getItemOffsets(outRect, itemPosition, parent)
                if (itemPosition == list.size - 1) {
                    outRect?.bottom = px.x(48)
                } else {
                    outRect?.top = 0
                }
            }
        })
    }

    override fun recycleView() {}

    var list = mutableListOf<SelectXj>()
    //刷新
    fun update() {
        Uri.selectfbtj(activity) {
            list.clear()
            list.addAll(it)
            adapter?.notifyDataSetChanged()
            if (list.size <= 0) {
                Toast.show("暂无巡检信息")
            }
        }
    }

    override fun onCreateView(context: Context): View? {
        var utype = MicrometerTable.getInstance().getUser().getUtype().trim()
        return context.UI {
            verticalLayout {
                backgroundColor = Color.parseColor("#F2F2F2")
                var topbar = Titlebar.topBar(context as Activity, "分开巡检", Color.TRANSPARENT)
                topbar.rightTextView?.apply {
                    text = "退出"
                    onClick {
                        loginOrOut(false)
                    }
                }
                topbar.view?.setBackgroundColor(Color.WHITE)
                topbar.textColor = Color.BLACK
                topbar.shadow = true


                addView(topbar.view)
                relativeLayout {
                    recyclerView = recyclerView {
                        var linearLayoutManager = LinearLayoutManager(owner)
                        linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
                        layoutManager = linearLayoutManager
                    }.lparams {
                        width = matchParent
                        height = matchParent
                        topOf(px.id("relaease"))
                    }

                    //刷新按钮
                    var refresh = RoundTextView(owner).apply {
                        all_radius = px.x(100f)
                        background = resources.getDrawable(R.mipmap.refresh)
                        onClick {
                            //刷新事件
                            update()
                        }
                    }.lparams {
                        width = px.y(100)
                        height = px.y(100)
                        bottomMargin = px.y(200)
                        alignParentBottom()
                        centerHorizontally()
                    }
                    addView(refresh)

                    if (utype.equals("4")) {
                        //组长
                        textView {
                            id = px.id("relaease")
                            gravity = Gravity.CENTER
                            backgroundColor = Color.parseColor("#00CCFF")
                            text = "发布"
                            textSize = px.textSizeX(32)
                            textColor = Color.WHITE
                            onClick {
                                //创建千分表
                                CreateSeparateDailog.getInstance(activity)
                            }
                        }.lparams {
                            width = matchParent
                            height = px.y(100)
                            alignParentBottom()
                        }
                    } else {
                    }

                }.lparams {
                    width = matchParent
                    height = matchParent
                }
            }
        }.view
    }

    //true登录，false退出登录
    private fun loginOrOut(login: Boolean) {
        LoginDialog.getInstance(activity, login, object : BaseListenner<Any> {
            override fun onResult(result: Any) {
                //登录成功回调

            }
        })
        dismiss()
    }

    class MyViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView) {
        val time by lazy { itemView?.findViewById<TextView>(px.id("time")) }
        val name by lazy { itemView?.findViewById<TextView>(px.id("name")) }
        val stname by lazy { itemView?.findViewById<TextView>(px.id("stname")) }
        val type by lazy { itemView?.findViewById<TextView>(px.id("type")) }
        val upload by lazy { itemView?.findViewById<Button>(px.id("upload")) }
        val delete by lazy { itemView?.findViewById<Button>(px.id("delete")) }
        val auto by lazy { itemView?.findViewById<AutoLinefeedLayout>(px.id("auto")) }
        val xz_name by lazy { itemView?.findViewById<TextView>(px.id("xz_name")) }
        val update by lazy { itemView?.findViewById<Button>(px.id("update")) }

    }

    class MyAdapter(var activity: BaseActivity, var separateDialog: SeparateDialog, var list: MutableList<SelectXj>) : Adapter<MyViewHolder>() {

        fun textSytle(textView: TextView) {
            textView?.apply {
                textColor = Color.BLACK
                textSize = px.textSizeX(28)
            }
        }

        var general = AssetsUtils.getInstance().getBitmapFromAssets("自动登录/square_general.png", 0, true)
        var selected = AssetsUtils.getInstance().getBitmapFromAssets("自动登录/square_selected.png", 0, true)
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
            general = Bitmap.createScaledBitmap(general, px.x(68), px.x(68), true)
            selected = Bitmap.createScaledBitmap(selected, px.x(68), px.x(68), true)
            var view = parent.context.UI {
                verticalLayout {
                    var layoutParams = ViewGroup.LayoutParams(px.realWidth().toInt(), wrapContent)
                    setLayoutParams(layoutParams)
                    gravity = Gravity.CENTER_HORIZONTAL
                    verticalLayout {
                        topPadding = px.x(24)
                        leftPadding = px.x(24)
                        bottomPadding = px.x(24)
                        backgroundColor = Color.WHITE
                        textView {
                            id = px.id("xz_name")
                            text = "巡检小组名称："
                            textSytle(this)
                        }
                        textView {
                            id = px.id("time")
                            text = "时间：2018-5-6 09:00"
                            textSytle(this)
                        }.lparams {
                            topMargin = px.x(24)
                        }
                        textView {
                            id = px.id("name")
                            text = "养老机构：上海普陀敬老院"
                            textSytle(this)
                        }.lparams {
                            topMargin = px.x(24)
                        }
                        textView {
                            id = px.id("stname")
                            text = "题目类型：普陀区长期护理保险定点护理服务机构"
                            textSytle(this)
                        }.lparams {
                            topMargin = px.x(24)
                        }
                        linearLayout {
                            textView {
                                text = "提交情况："
                                textSytle(this)
                            }.lparams {
                            }
                            var auto = AutoLinefeedLayout(owner).apply {
                                id = px.id("auto")
                            }.lparams {
                                width = matchParent
                                height = wrapContent
                                topMargin = px.x(3)
                            }
                            addView(auto)
                        }.lparams {
                            width = matchParent
                            topMargin = px.x(12)
                        }

                        linearLayout {
                            textView {
                                id = px.id("type")
                                text = "状态：未上传"
                                textSytle(this)
                                textColor = Color.parseColor("#FF4E4E")
                            }.lparams {
                            }

                            button {
                                id = px.id("update")
                                backgroundColor = Color.parseColor("#00FF80")
                                text = "修改"
                                textColor = Color.WHITE
                                textSize = px.textSizeX(28)
                                padding = 0
                            }.lparams {
                                width = px.x(100)
                                height = px.x(50)
                                leftMargin = px.x(50)
                            }

                            var utype = MicrometerTable.getInstance().getUser().getUtype().trim()
                            if (utype.equals("4")) {
                                //组长
                                button {
                                    id = px.id("upload")
                                    backgroundColor = Color.parseColor("#33CCFF")
                                    text = "上传"
                                    textColor = Color.WHITE
                                    textSize = px.textSizeX(28)
                                    padding = 0
                                }.lparams {
                                    width = px.x(100)
                                    height = px.x(50)
                                    leftMargin = px.x(50)
                                }
                                button {
                                    id = px.id("delete")
                                    backgroundColor = Color.parseColor("#FF0000")
                                    text = "删除"
                                    textColor = Color.WHITE
                                    textSize = px.textSizeX(28)
                                    padding = 0
                                }.lparams {
                                    width = px.x(100)
                                    height = px.x(50)
                                    leftMargin = px.x(50)
                                }
                            } else {
                                //组员
                            }

                        }.lparams {
                            width = matchParent
                            topMargin = px.x(24)
                        }

                    }.lparams {
                        width = px.x(700)
                        height = wrapContent
                        topMargin = px.x(48)
                    }
                }
            }.view
            return MyViewHolder(view)
        }

        override fun getItemCount(): Int {
            return list.size
        }

        val alert by lazy { AlertDialog(activity) }
        override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
            holder.xz_name?.setText("巡检小组名称：\t" + list[position].xz_name)
            holder.time?.setText("时间:\t" + list[position].time)
            holder.name?.setText("养老机构：\t" + list[position].name)
            holder.stname?.setText("题目类型：\t" + list[position].stname)
            if (list[position].type.equals("1")) {
                holder.type?.setText("状态：\t未上传")
                holder.upload?.visibility = View.VISIBLE
                holder.upload?.isEnabled = true

                //修改题目
                if (Uri.haCache(list[position].pid)) {
                    holder.update?.visibility = View.VISIBLE
                } else {
                    holder.update?.visibility = View.INVISIBLE
                }
                holder.update?.onClick {
                    //修改题目
                    var list1 = Uri.getCacheTopicinfo(list[position].pid)

                    if (list1?.size ?: 0 > 0) {
                        list1?.let {
                            Uri.topicinfoList = list1//千分表
                            var list2 = Uri.getCacheHostoryTopicinfo(list[position].pid)
                            list2?.let {
                                Uri.topicsHostoryQF = list2//历史整改
                            }
                            //千分表评分系统
                            SeparateTableOSDialog.getInstance(activity, list[position].pid)
                        }
                    } else {
                        Toast.show("暂无缓存题目")
                    }
                }

            } else if (list[position].type.equals("2")) {
                holder.type?.setText("状态：\t已上传")
                holder.upload?.isEnabled = false
                holder.upload?.visibility = View.INVISIBLE

                holder.update?.visibility = View.INVISIBLE
            }
            holder.upload?.onClick {
                //上传
                SeparateUploadDailog.getInstance(activity, separateDialog, list[position].pid)
            }
            holder.delete?.onClick {
                //删除
                alert.little(false).title("警告").mession("确定删除?").positive {
                    Uri.delete(activity, list[position].id) {
                        Toast.show(it)
                        separateDialog.update()
                    }
                }.show()
            }

            var tmfls = JSonUtils.parseArray(list[position].tmfl, ArrayList<tmfl>())
            holder.auto?.apply {
                removeAllViews()
                tmfls?.apply {
                    if (size > 0) {
                        for (i in 0..size - 1) {
                            linearLayout {
                                checkBox {
                                    text = "\u0020" + get(i).fl_name + "\u3000"
                                    textColor = Color.BLACK
                                    SelectorUtils.selectorDrawable(this, general, selected)
                                    SelectorUtils.selectorTextColor(this, Color.parseColor("#929292"), Color.parseColor("#CC6600"))
                                    textSize = px.textSizeX(28)
                                    isEnabled = false
                                    isChecked = get(i).fl_type.equals("2")
                                }.lparams {
                                    bottomMargin = px.x(6)
                                    //宽和高默认就是wrapContent
                                }
                            }
                        }
                    }
                }

            }

            holder.itemView.onClick {
                CreateSeparateDailog2(activity, list[position].id, list[position].pid)
            }


        }
    }

}